package com.jinsi.controller;

import com.jinsi.pojo.ScUser;
import com.jinsi.service.impl.ScUserServiceImpl;
import com.jinsi.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    @Autowired
    private ScUserServiceImpl service;

    @ResponseBody
    @RequestMapping("/getLoginByAccount")
    public Map<String,Object> getLoginByAccount(ScUser user,HttpSession session){
        Map<String,Object> map = new HashMap<>();
        String md5Pwd = Md5Utils.getMd5Pwd(user);
        ScUser login = service.getLoginByAccountAndPwd(user.getUserAccount(),md5Pwd);
        if (login != null){
            session.setAttribute("user",login);
            ScUser u = (ScUser) session.getAttribute("user");
            map.put("state","200");
            map.put("user",u);
        }else {
            map.put("state","400");
        }
        return map;
    }

    @ResponseBody
    @RequestMapping("/getLoginByPhone")
    public Map<String,Object> getLoginByPhone(String userPhone, String yzm, HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        HttpSession session = request.getSession();
        Integer param  = (Integer) session.getAttribute("Param");

        if (!param.toString().equals(yzm)){
            map.put("state","401");
        }else {
            ScUser login = service.getLoginByPhone(userPhone);
            if (login != null){

                session.setAttribute("user",login);
                ScUser user = (ScUser) session.getAttribute("user");
                map.put("state","200");
                map.put("user",user);
            }else {
                map.put("state","400");
            }
        }
        return map;
    }

    @ResponseBody
    @RequestMapping("/getRegister")
    public Map<String,String> getRegister(ScUser user,String yzm,HttpSession session){
        Map<String, String> map = new HashMap<>();
        Integer param  = (Integer) session.getAttribute("Param");
        String md5Pwd = Md5Utils.getMd5Pwd(user);
        user.setUserPwd(md5Pwd);
        user.setUserCreateDate(new Date());
        if (!param.toString().equals(yzm)){
            map.put("state","401");
        }else {
            try {
                service.getRegister(user);
                map.put("state","200");
            } catch (Exception e) {
                map.put("state","400");
                e.printStackTrace();
            }
        }
        return map;
    }


}
